<!--搜索弹窗-->
<script setup>
import {nextTick, ref, toRefs, watch} from "vue";
import {ForumType} from "@ginstone/nga-api/dist/src/enums/ForumType";
import {routeNames} from "@/router";
import {useRoute, useRouter} from "vue-router";

const props = defineProps({
  // 可选版面
  data: {type: Array},
  // 搜索精华
  recommend: Boolean,
  // 初始关键字
  searchKey: String,
})
const router = useRouter();
const route = useRoute();

const {content, recommend, searchKey} = toRefs(props)

const keyword = ref();
// 选中的版面
const selected = ref();
// 路由query参数
const query = ref({
  content: undefined,
  recommend: undefined,
})

// 初始化
const init = () => {
  // 初始关键字
  if (searchKey.value) keyword.value = searchKey.value;
  // 初始精华选项
  query.value.recommend = recommend.value ? 1 : undefined;
  // 默认选中最后一项
  selected.value = data.value.length - 1

  nextTick(() => {
    setTimeout(() => {
      const e = document.getElementById("search_input")
      e.focus()
      e.select()
    }, 100)
  })
}

// 执行搜索
const search = () => {
  const {id, name, type} = data.value[selected.value]
  // 路由名称
  if (!keyword.value) {
    return;
  }
  const target = {
    // 路由名称
    name: (type === ForumType.FORUM) ? routeNames.thread.forumSearch : routeNames.thread.colSearch,
    params: {
      id,
      keyword: keyword.value
    },
    query: query.value,
  }
  // 切换路由
  router.push(target)
  popover.value.hide()
}
const popover = ref();

const {data, modelValue} = toRefs(props)

watch(route, () => {
  popover.value.hide()
})
</script>

<template>
  <el-popover
      ref="popover"
      placement="bottom"
      title="搜索"
      trigger="click"
      width="400"
      @show="init"
  >
    <div id="search-popover">
      <!--选择搜索版面-->
      <el-radio-group v-model="selected">
        <template v-for="(item,index) in data">
          <el-radio :label="index">
            [{{ item.type }}] {{ item.name }}
          </el-radio>
        </template>
      </el-radio-group>
      <!--填写关键字-->
      <el-input id="search_input" v-model="keyword" placeholder="请填写关键字, 尽量不少于2字, 回车确认" @keyup.enter="search"/>
      <div v-if="!keyword" style="color:red">关键字不能为空</div>
      <!--是否搜索主楼-->
      <el-switch v-model="query.content" :active-value="1" :inactive-value="undefined" active-text="搜索主楼正文" class="search-switch"/>
      <!--是否仅搜索精华-->
      <el-switch v-model="query.recommend" :active-value="1" :inactive-value="undefined" active-text="仅精华" class="search-switch"/>
      <el-button type="primary" @click="search">搜索</el-button>
    </div>
    <template #reference>
      <slot></slot>
    </template>
  </el-popover>
</template>

<style scoped>
.search-switch {
  margin-right: 5px;
}

.forum-radio {
  display: block;
}
</style>